package com.frog.framework.s3.factory;

import com.frog.framework.s3.config.S3Config;
import org.springframework.util.Assert;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.utils.StringUtils;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wuqiong 2022-10-26
 * @description
 */
public class S3EndpointFactory {

    private static final Map<String, S3Client> endpointMap = new ConcurrentHashMap<>();
    private static final String defaultStr = "defaults";

    /**
     * get s3 client endpoint
     *
     * @param clientName
     * @return S3Client
     * @author wuqiong 2022/10/26 15:52
     */
    public static S3Client getS3Client(String clientName) {
        if (StringUtils.isBlank(clientName)) clientName = defaultStr;
        return endpointMap.get(clientName);
    }

    /**
     * create batch s3 client
     *
     * @param sqsConfig
     * @author wuqiong 2022/10/26 15:52
     */
    public static void createBatchByConfig(S3Config s3Config) {
        Assert.isTrue(!s3Config.getInstances().isEmpty(), "S3 config 为空,请检查");
        if (!s3Config.getInstances().containsKey(defaultStr)) {
            Optional<String> first = s3Config.getInstances().keySet().stream().findFirst();
            S3Client S3Client = createS3Client(first.get(), s3Config.getInstances().get(first.get()));
            endpointMap.put(first.get(), S3Client);
            endpointMap.put(defaultStr, S3Client);
        }
        s3Config.getInstances().forEach((k, v) -> endpointMap.put(k, createS3Client(k, v)));
    }

    /**
     * create s3 client by config endpointInstance
     *
     * @return S3Client
     * @author wuqiong 2022/10/26 15:52
     */
    public static synchronized S3Client createS3Client(String clientName, S3Config.EndpointInstance endpointInstance) {
        Assert.isTrue(endpointInstance != null, "s3 endpointInstance is null , please check ");
        if (endpointMap.containsKey(clientName)) return endpointMap.get(clientName);
        S3ClientBuilder builder = S3Client.builder();
        builder.region(Region.of(endpointInstance.getRegion()));
        if (StringUtils.isNotBlank(endpointInstance.getAccessKeyId()) && StringUtils.isNotBlank(endpointInstance.getSecretAccessKey())) {
            builder.credentialsProvider(StaticCredentialsProvider.create(
                    AwsBasicCredentials.create(endpointInstance.getAccessKeyId(), endpointInstance.getSecretAccessKey())));
        }
        return builder.build();
    }

}
